/*
 * Copyright (C) 2012 scchang <scchang@caltech.edu>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package ogame.utilities.datastorage.subtables;

import com.almworks.sqlite4java.SQLiteConnection;
import com.almworks.sqlite4java.SQLiteException;
import com.almworks.sqlite4java.SQLiteStatement;
import ogame.utilities.Constants;
import ogame.utilities.Coords;
import ogame.utilities.Resources;
import ogame.utilities.buildings.Buildings;
import ogame.utilities.datastorage.OgameDataStorage;
import ogame.utilities.defenses.Defenses;
import ogame.utilities.planets.Planet;
import ogame.utilities.ships.Ships;

/**
 *
 * @author scchang <scchang@caltech.edu>
 */
public class PlanetTable {
    /**
     * Connection for the current database.
     */
    protected SQLiteConnection db;
    
    /**
     * Connection interface for all the other tables.
     */
    protected OgameDataStorage ogameDataStorage;
    
    ///////////////////////////////////////////////////////////////////////////
    /**
     * Constructs and initializes a new planet table interface.
     * @param db, Already opened db
     */
    public PlanetTable(SQLiteConnection db, OgameDataStorage ogameDataStorage){
        this.db = db;
        this.ogameDataStorage = ogameDataStorage;
        this.initializePlanetTable();
    }
    
    ///////////////////////////////////////////////////////////////////////////
    /**
     * Initializes the planet table within the current database.
     */
    protected void initializePlanetTable(){
        // Simple Inject
        String sql_inject = "CREATE TABLE IF NOT EXISTS Planets (";
        for(int i = 0 ; i < Constants.DATA_STORAGE_PLANETS_COLS.length; ++i){
            sql_inject += " " + Constants.DATA_STORAGE_PLANETS_COLS[i];
            if(i < Constants.DATA_STORAGE_PLANETS_COLS.length - 1){
                sql_inject += ",";
            }
        }
        sql_inject += ")";
        
        try{
            this.db.exec(sql_inject);
        }catch(SQLiteException e){
            e.printStackTrace();
            System.out.println("Unable to create planet table.");
        }
    }
    
    /**
     * Public method to get planet with the given id from internal database.
     * @param id, The id of the planet needed.
     * @return The planet from internal database.
     */
    public Planet getPlanetFromID(int id){
        // Simple Inject
        String sql_inject = "SELECT * FROM Planets WHERE planet_id=?";
        try{
            SQLiteStatement st = this.db.prepare(sql_inject);
            st.bind(1, id);
            
            if(st.step()){
                
                int planet_id = st.columnInt(0);
                int player_id = st.columnInt(1);
                String planet_name = st.columnString(2);
                int galaxy = st.columnInt(3);
                int system = st.columnInt(4);
                int slot = st.columnInt(5);
                byte[] resources = st.columnBlob(6);
                byte[] buildings = st.columnBlob(7);
                byte[] fleet = st.columnBlob(8);
                byte[] defense = st.columnBlob(9);

                Coords coords = new Coords(galaxy, system, slot);
                Resources result_resources = Resources.parseResources(resources);
                Buildings result_buildings = Buildings.parseBuildings(buildings);
                Ships result_fleet = Ships.parseShips(fleet);
                Defenses result_defense = Defenses.parseDefenses(defense);
                
                // Planet player should be set later
                Planet result = new Planet(null, planet_name, coords);
                result.setBuildings(result_buildings);
                result.setResources(result_resources);
                result.setShips(result_fleet);
                result.setDefenses(result_defense);
                
                return result;
            }
            return null;
        }catch(SQLiteException e){
            e.printStackTrace();
            System.out.println("Unable to find planet.");
            return null;
        }
    }

    ///////////////////////////////////////////////////////////////////////////
    /**
     * Determines if the given planet is already in table. If so, an update is 
     * needed.
     * @param planet, The planet that could be in the table
     * @return integer of the p_id, -1 if unable to 
     */
    public int getPlanetID(Planet planet){
        try{
            SQLiteStatement st = this.db.prepare("SELECT planet_id FROM Planets WHERE galaxy=?1 AND system=?2 "
                    + "AND slot=?3");
            Coords coords = planet.getCoords();
            st.bind(1, coords.getGalaxy());
            st.bind(2, coords.getSystem());
            st.bind(3, coords.getPlanet());
            
            if(st.step()){
                return st.columnInt(0);
            }
            return -1;
        }catch(SQLiteException e){
            System.out.println("Unable to determine if planet is in table.");
            e.printStackTrace();
            return -1;
        }
        
    }
    
    /**
     * Modifies table correctly if a row already exists or not.
     * @param planet, The planet to be inserted
     * @return Boolean if the given planet is in the table
     */
    public boolean modifyTable(Planet planet){
        try{
            SQLiteStatement st = null;
            int planetID = this.getPlanetID(planet);
            
            if(planetID != -1){
                // The planet is already in the database
                st = this.db.prepare("UPDATE Planets SET "
                        + "resources=?1, "
                        + "buildings=?2, "
                        + "fleet=?3, "
                        + "defense=?4 WHERE planet_id=?5");
                byte[] resources = planet.getResources().encode();
                byte[] buildings = planet.getBuildings().encode();
                byte[] fleet = planet.getShips().encode();
                byte[] defense = planet.getDefenses().encode();
                
                st.bind(1, resources);
                st.bind(2, buildings);
                st.bind(3, fleet);
                st.bind(4, defense);
                st.bind(5, planetID);

                st.step();
                st.dispose();
                return true;
            }else{
                // Planet is a new one 
                int nextPlanetID = this.ogameDataStorage.getGeneralTable().getNextPlanetID();
                
                if(nextPlanetID == -1){
                    System.out.println("In planetTable::modifytable, Unable to get next planet id.");
                    return false;
                }
                
                if(!this.ogameDataStorage.getPlayerTable()
                        .updatePlayerWithNewPlanet(planet.getPlayer(), nextPlanetID)){
                    System.out.println("In planetTable::modifytable, Unable to update player with new planet.");
                    return false;
                }
                
                // Because the update player creates players, it should now have an id
                int playerID = this.ogameDataStorage.getPlayerTable().getPlayerID(planet.getPlayer());
                if(playerID == -1){
                    System.out.println("In planetTable::modifytable, Unable to find player id.");
                    return false;
                }
                
                st = this.db.prepare("INSERT INTO Planets VALUES "
                        + "(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)");
                
                String planetName = planet.getName();
                int galaxy = planet.getCoords().getGalaxy();
                int system = planet.getCoords().getSystem();
                int slot = planet.getCoords().getPlanet();
                byte[] resources = planet.getResources().encode();
                byte[] buildings = planet.getBuildings().encode();
                byte[] ships = planet.getShips().encode();
                byte[] defense = planet.getDefenses().encode();
                
                st.bind(1, nextPlanetID);
                st.bind(2, playerID);
                st.bind(3, planetName);
                st.bind(4, galaxy);
                st.bind(5, system);
                st.bind(6, slot);
                st.bind(7, resources);
                st.bind(8, buildings);
                st.bind(9, ships);
                st.bind(10, defense);
                
                st.step();
                st.dispose();                
                if(!this.ogameDataStorage.getGeneralTable().incrementPlanetID()){
                    System.out.println("Unable to increment planet id.");

                    return false;
                }
                return true;
            }
        }catch(SQLiteException e){
            System.out.println("Unable to modify table with passed planet.");
            e.printStackTrace();
            return false;
        }
    }

}
